/**
 *       Copyright (c) 2012 Lukas Zaruba
 *
 *   This file is part of Robot Playground.
 *
 *   Robot Playground is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   Robot Playground is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with Robot Playground. If not, see <http://www.gnu.org/licenses/>.
 */
package net.zarubsys.robotplayground.dummydevice;

import java.util.concurrent.locks.ReentrantLock;

import net.zarubsys.robotplayground.core.Environment;
import net.zarubsys.robotplayground.core.device.IDevice;

/**
 * DummyDevice
 * 
 * Please note that setters should be manipulated only after acquiring a lock using {@link #lockMovementsAccess()} 
 * method or an Exception will be thrown. Be sure to release the lock afterwards in all cases, preferably using the "finally" branch. 
 *
 * @author Lukas Zaruba, lukas.zaruba@gmail.com
 */
public class DummyDevice implements IDevice<DummyDeviceConfiguration> {
	
	public static final String ID = "dummyDevice";
	
	private int x;
	private int y;
	private int direction; // in degrees
	
	final ReentrantLock movementsLock = new ReentrantLock();

	@Override
	public void init(DummyDeviceConfiguration configuration, Environment env) {
		this.x = configuration.getInitialX();
		this.y = configuration.getInitialY();
		this.direction = configuration.getDirection();
	}

	@Override
	public void close() {
		// ignored, nothing to be closed
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		checkLockOwnership();
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		checkLockOwnership();
		this.y = y;
	}

	public int getDirection() {
		return direction;
	}

	public void setDirection(int direction) {
		checkLockOwnership();
		this.direction = direction;
	}
	
	public void lockMovementsAccess() {
		movementsLock.lock();
	}
	
	public void unlockMovementsAccess() {
		movementsLock.unlock();
	}
	
	private void checkLockOwnership() {
		if (!movementsLock.isHeldByCurrentThread()) {
			throw new IllegalStateException("Illegal access to a dummy device method without acquiring the lock first");
		}
	}
	
	@Override
	public String getId() {
		return ID;
	}
	
}

